<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>歌词实时滚动的原方法</title>
    <script src="js/ajaxRequest.js"></script>
</head>

<body>
    <script>
        // 歌词实时滚动的原方法

        // 渲染歌词
        function renderLyrics(time, lyric) {

            let lyricLength = lyric.length;

            for (let i = 0; i < lyricLength; i++) {
                let lineLyric = document.createElement('div');
                lyricBox.appendChild(lineLyric);
                lineLyric.className = 'line-lyric';
                lineLyric.setAttribute('data-number', i);
                lineLyric.innerHTML = lyric[i];
            }

            // 每行歌词
            let eachLineLyric = document.querySelectorAll('.line-lyric');

            // 存放歌词时间的数组
            let lyricArr = [];

            for (let i = 0; i < time.length; i++) {
                lyricArr[i] = getMilisecond(time[i]);
            }

            console.log(lyricArr);

            let cunt = 0;

            // 音乐进度更新时匹配时间
            audio.addEventListener('timeupdate', function () {

                // 把音乐进度转化为毫秒
                let audioTime = parseInt(this.currentTime * 1000);

                // 遍历time数组，把每个时间都转化为毫秒形式
                for (let i = 0; i < time.length; i++) {
                    // 当前时间与当前歌词的时间差
                    let timeLag = audioTime - lyricArr[i];
                    // 当前时间与下句歌词的时间差
                    let nextTimeLag = audioTime - lyricArr[i + 1];

                    // 当前时间与此句歌词的时间差小于200毫秒，展示当前歌词
                    if (timeLag <= 200 && timeLag > 0) {
                        // 字体样式改变
                        eachLineLyric[i].className = 'current-lyric';
                        // 滚动效果
                        lyricBox.style.top = 360 - (i + 1) * 60 + 'px';
                    }

                    // 当前时间与下句歌词的时间差小于200毫秒，展示下句歌词
                    if (nextTimeLag <= 200 && nextTimeLag > 0) {
                        // 字体样式复原
                        for (let i = 0; i < lyricLength; i++) {
                            eachLineLyric[i].className = 'line-lyric';
                        }
                    }
                }
            })

            // 点击歌词 实现进度更新
            for (let i = 0; i < lyricLength; i++) {
                eachLineLyric[i].addEventListener('click', () => {
                    audio.currentTime = parseInt(lyricArr[i] / 1000);
                })
            }

            // 音乐结束时，恢复原状态
            audio.addEventListener('ended', function () {
                lyricBox.style.top = '360px';

                for (let i = 0; i < lyricLength; i++) {
                    eachLineLyric[i].className = 'line-lyric';
                }
            })
        }
    </script>
</body>

</html>